/**
 * 团队管理js
 *
 */
var pageCurr;
var form;
$(function () {
    layui.use(['table', 'upload', 'form'], function () {
        var table = layui.table;
        form = layui.form;

        var $ = layui.jquery
            , upload = layui.upload;

        tableIns = table.render({
            id: 'menberId',
            elem: '#memberList',
            url: '/team/admin/getAllMembers',
            method: 'get', //默认：get请求
            cellMinWidth: 80,
            toolbar: 'default', //开启工具栏，此处显示默认图标
            page: true,
            request: {
                pageName: 'currPage', //页码的参数名称，默认：pageNum
                limitName: 'pageSize' //每页数据量的参数名，默认：pageSize
            },
            response: {
                statusName: 'code', //数据状态的字段名称，默认：code
                statusCode: 0, //成功的状态码，默认：0
                countName: 'total', //数据总数的字段名称，默认：count
                dataName: 'datas' //数据列表的字段名称，默认：data
            },
            /**
             * 修改table.js 中的源码得到的自定义方法。解决多层json嵌套无法渲染表格的问题
             */
            beforeRender: function (res) {
                res.total = res.page.total;
            },
            cols: [[
                {type: 'checkbox', width: '3%', fixed: 'left'}
                , {field: 'memberName', title: '成员姓名', align: 'center', width: "20%"}
                , {field: 'memberPosition', title: '成员职位', align: 'center', width: "17%"}
                , {
                    field: 'memberImg', title: '成员照片', align: 'center', width: "35%",
                    templet: function (d) {
                        return '<div class="memberImg" style="height: 60px;line-height: 60px">' +
                            '<img src=' + d.memberImg + '></div>'
                    }
                }
                , {fixed: 'right', title: '操作', align: 'center', toolbar: '#optBar', width: "25%"}
            ]],
            done: function (res, curr, count) {
                $(".layui-table-main  tr").each(function (index, val) {
                    $($(".layui-table-fixed .layui-table-body tbody tr")[index]).height($(val).height());
                });
                pageCurr = curr;
                layer.photos({
                    photos: '.memberImg',
                    anim: 3
                })
            }
        });

        var form = layui.form
            , layer = layui.layer;

        var imgUrl;

        var img;

        //图片上传
        var uploadInst = upload.render({
            elem: '#memberImg'
            , url: '/file/imgUpload'
            , before: function (obj) {

            }
            , done: function (res) {

                //如果上传失败
                if (res.code < 0) {
                    return layer.msg('上传失败');
                }
                imgUrl=res.url;
                //上传成功
                $('#demoMember').attr('src', res.url); //照片回显
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });

        //图片上传
        var uploadImg = upload.render({
            elem: '#Img'
            , url: '/file/imgUpload'
            , before: function (obj) {

            }
            , done: function (res) {

                //如果上传失败
                if (res.code < 0) {
                    return layer.msg('上传失败');
                }
                imgUrl=res.url;
                //上传成功
                $('#MemberPhoto').attr('src', res.url); //照片回显
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#memberText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadImg.upload();
                });
            }
        });

        //监听工具条
        table.on('tool(memberTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                //删除
                deleteMember(data, obj);

            } else if (obj.event === 'edit') {
                //编辑成员信息
                openEdit(data,"修改成员信息");
                img=data.memberImg;
            }
        });

        //监听事件
        table.on('toolbar(memberTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id),
                data = checkStatus.data; //获取选中的数据;
            switch (obj.event) {
                case 'add':
                    addMember("添加成员信息");
                    break;
                case 'update':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('只能同时编辑一个');
                    } else {
                        openEdit(checkStatus.data[0],"修改成员信息");
                    }
                    break;
                case 'delete':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('请勿同时删除多行数据');
                    } else {
                        deleteMember(checkStatus.data[0], obj);
                    }
                    break;
            }
        });

        //监听提交
        form.on('submit(teamSubmit)', function (data) {

            // console.log(data);

           var memberName = data.field.memberName;
            var memberPosition = data.field.memberPosition;
            var menberId = data.field.menberId;
            var memberImg;

            if (imgUrl!=null){
                memberImg=imgUrl;
            }else{
                memberImg=img;
            }

            $.ajax({
                type: "POST",
                url: "/team/admin/updateMember",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify({
                    menberId: menberId,
                    memberName: memberName,
                    memberPosition: memberPosition,
                    memberImg: memberImg
                }),
                datatype: 'json',
                error: function () {
                    layer.alert("更新失败");
                    layer.closeAll();
                },
                success: function (res) {

                    if (res.code == 0) {
                        layer.alert("更新成功");
                        layer.closeAll();
                        load(data);
                    } else {
                        layer.alert("更新失败");
                        layer.closeAll();
                    }
                }
            });

            return false;
        });

        //监听提交
        form.on('submit(memberSubmit)', function (data) {

            console.log(data);

            var memberName = data.field.memberName;
            var memberPosition = data.field.memberPosition;
            var memberImg;

            if (imgUrl!=null){
                memberImg=imgUrl;
            }else{
                memberImg=img;
            }

            $.ajax({
                type: "POST",
                url: "/team/admin/addMember",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify({
                    memberName: memberName,
                    memberPosition: memberPosition,
                    memberImg: memberImg
                }),
                datatype: 'json',
                error: function () {
                    layer.alert("添加失败");
                    layer.closeAll();
                },
                success: function (res) {

                    if (res.code == 0) {
                        layer.alert("添加成功");
                        load(data);
                    } else {
                        layer.alert("添加失败");
                        layer.closeAll();
                    }
                }
            });

            return false;
        });
    });

});

function addMember(title) {
    layer.open({
        type: 1,
        title: title,
        fixed: false,
        resize: false,
        shadeClose: true,
        area: ['550px'],
        content: $('#addMember'),
        end: function () {

        }
    });
}

//打开编辑框
function openEdit(data,title) {
    if (data == null) {
        $("#id").val("");
    } else {
        //回显数据
        $("#id").val(data.menberId);
        $("#memberName").val(data.memberName);
        $("#memberPosition").val(data.memberPosition);
        $('#demoMember').attr('src', data.memberImg);
    }

    layer.open({
        type: 1,
        title: title,
        fixed: false,
        resize: false,
        shadeClose: true,
        area: ['550px'],
        content: $('#setMember'),
        end: function () {

        }
    });

}

//重新加载table
function load(obj) {
    tableIns.reload({
        where: obj.field
        , page: {
            curr: pageCurr //从当前页码开始
        }
    });
}


function deleteMember(data, obj) {
    //删除
    if (null != data.menberId) {
        layer.confirm('您确定要删除吗？', {
            btn: ['确认', '取消'] //按钮
        }, function () {
            $.post("/team/admin/deleteMember", {"memberId": data.menberId}, function (data) {
                if (data.code == 0) {
                    layer.alert("删除成功", function () {
                        layer.closeAll();
                        load(obj);
                    });
                } else {
                    layer.alert("删除失败");
                }
            });
        }, function () {
            layer.closeAll();
        });
    }
}
